#pragma once 
#include <unordered_map>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdint>
#include <memory>
#include <unistd.h>
#include <vector>

class Session
{
public:
    Session(const std::string& username,const std::string& status)
        :_username(username),_status(status)
        {
            _create_time = time(nullptr);
        }
    std::string _username;
    std::string _status;
    uint64_t _create_time;
    ~Session(){}
};

using session_ptr = std::shared_ptr<Session>;
using t = std::pair<std::string,session_ptr>;

class SessionManager
{
public:
    static SessionManager* GetInstance()
    {
        if (_instance == nullptr)
        {
            _instance = new SessionManager();
            return _instance;
        }
        return _instance;
    } 
    ~SessionManager(){ LOG(LogLevel::DEBUG) << "管理被释放了!!!";}
    std::string AddSession(session_ptr s)
    {
        uint32_t randomid = rand() + time(nullptr); // 随机数+时间
        std::string sessionid = std::to_string(randomid);
        _sessions.push_back(std::make_pair(sessionid, s)); //创建 ssessionid和Session对象的映射关系 (哈希表)
        // OnlineUser(); //这里使用添加的用户的
        return sessionid;
    }
    void printstr(std::string s)
    {
        std::cout << " str: " << s << " size: " << s.size() << std::endl;
        for (int i = 0; i < s.size();i++)
        {
            std::cout << " i: " << s[i] << " ";
        }
        std::cout << std::endl;
    }
    session_ptr GetSession(std::string sessionid)
    {
        // OnlineUser(); //打印在线用户
        // LOG(LogLevel::DEBUG) << "找的到吗? " << _sessions.find(sessionid);
        LOG(LogLevel::DEBUG) << "进行比较的id: " << sessionid;
        for (auto& x : _sessions)
        {
            if (sessionid == x.first)
            {
                return x.second;
            }
        }
        return nullptr;
    }
    void OnlineUser()
    {
        std::cout << "在线用户: " << std::endl;
        for (auto& x : _sessions)
        {
            std::cout << x.second->_username << " id: " << x.first << std::endl;
        }
    }
private:
    SessionManager(){srand(time(nullptr) ^ getpid());}
    std::vector<t> _sessions;
    static SessionManager* _instance;
};

SessionManager* SessionManager::_instance = nullptr;
 